package cn.ubeta.b2c.navigation;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import cn.ubeta.b2c.BuildConfig;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.api.ApiUser;
import cn.ubeta.b2c.bean.AddressInfo;
import cn.ubeta.b2c.bean.ApiResp;
import cn.ubeta.b2c.bean.MeInfo;
import cn.ubeta.b2c.common.LoginCommon;
import cn.ubeta.b2c.user.CouponActivity;
import cn.ubeta.b2c.user.FavoriteActivity;
import cn.ubeta.b2c.user.FillBillActivity;
import cn.ubeta.b2c.user.LoginActivity;
import cn.ubeta.b2c.user.OrderActivity;
import cn.ubeta.b2c.user.RegisterActivity;
import cn.ubeta.b2c.user.address.AddressActivity;
import cn.ubeta.b2c.utils.AppConfig;
import cn.ubeta.b2c.utils.ToastHelper;
import cn.ubeta.b2c.widget.ItemView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static cn.ubeta.b2c.cart.CheckoutActivity.RECV_TIME;

/**
 * Created by denny on 16/8/17.
 */

public class MeFragment extends Fragment implements View.OnClickListener {

    private SimpleDraweeView mHeadPic;
    private TextView mTvName;
    private TextView mTvCouponCnt;
    private TextView mTvFavCnt;
    private TextView mTvAccountMan;

    // 地址
    private ItemView mItAddress;
    // 收货时间
    private ItemView mItReceiveTime;
    // 发票
    private ItemView mItBillInfo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_me, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mHeadPic = (SimpleDraweeView) view.findViewById(R.id.iv_header);
        mTvName = (TextView) view.findViewById(R.id.tv_name);
        mTvCouponCnt = (TextView) view.findViewById(R.id.tv_coupon_count);
        mTvFavCnt = (TextView) view.findViewById(R.id.tv_favorite_count);
        mTvAccountMan = (TextView) view.findViewById(R.id.tv_account_man);

        mHeadPic.setOnClickListener(this);
        mTvName.setOnClickListener(this);
        view.findViewById(R.id.ll_coupon).setOnClickListener(this);
        view.findViewById(R.id.ll_favorite).setOnClickListener(this);
        mTvAccountMan.setOnClickListener(this);

        // 地址
        mItAddress = ((ItemView) view.findViewById(R.id.it_address));
        mItAddress.setOnClickListener(v -> AddressActivity.gotoAddressList(getActivity()));

        // 收货时间
        mItReceiveTime = (ItemView) view.findViewById(R.id.it_recv_time);
        mItReceiveTime.setOnClickListener(v -> showRecvTimeDialog());

        // 发票
        mItBillInfo = (ItemView) view.findViewById(R.id.it_bill);
        mItBillInfo.setOnClickListener(v -> FillBillActivity.gotoActivityWithLogin(getContext(), FillBillActivity.class, true));

        // 订单
        view.findViewById(R.id.it_order).setOnClickListener(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 相当于onResume
        if (isVisibleToUser) {
            refreshView();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshView();
    }

    /**
     * 刷新视图
     */
    private void refreshView() {
        if (mTvName == null)
            return;

        if (LoginCommon.isLogin()) {
            //mTvName.setText(LoginHelper.getJdLoginHelper(getContext()).getUserAccount());
            //mTvName.setVisibility(VISIBLE);
            mTvAccountMan.setVisibility(VISIBLE);
            // 刷新数据
            setNickName(AppConfig.getNickName());
            mHeadPic.setImageURI(AppConfig.getAvatar());
            refreshData();
        } else {
            mTvName.setText("登录");
            mItAddress.updateDesc("请选择收货地址");
            mItReceiveTime.updateDesc("请选择配送时间");
            mItBillInfo.updateDesc("请填写发票信息");
            mTvAccountMan.setVisibility(GONE);
            setMeInfo(null);
        }
    }

    /**
     * 刷新地址
     */
    private void refreshAddress() {
        if (!LoginCommon.isLogin()) {
            mItAddress.updateDesc("请选择收货地址");
            return;
        }

        if (AppConfig.getPreConfigAddressInfo().getAddressId() > 0) {
            updateAddress();
        } else {
            ApiUser.getAddressList(1, new Callback<ApiResp<List<AddressInfo>>>() {

                @Override
                public void onResponse(Call<ApiResp<List<AddressInfo>>> call, Response<ApiResp<List<AddressInfo>>> res) {
                    if (res.body() != null) {
                        List<AddressInfo> data = res.body().getData();
                        if (data != null && data.size() > 0) {
                            // 如果没有默认地址则选择第一个
                            AddressInfo defaultAddr = data.get(0);
                            for (AddressInfo info : data) {
                                if (info.isAddressDefault()) {
                                    defaultAddr = info;
                                    break;
                                }
                            }
                            // 保存默认地址
                            AppConfig.savePreConfigAddress(defaultAddr);
                            // 更新展示
                            updateAddress();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ApiResp<List<AddressInfo>>> call, Throwable t) {
                    ToastHelper.show("获取默认地址失败，请手动选取");
                }
            });
        }
    }

    /**
     * 跟新地址展示
     */
    private void updateAddress() {
        if (AppConfig.getPreConfigAddressInfo().getAddressId() > 0) {
            mItAddress.updateDesc(AppConfig.getPreConfigAddressInfo().getDisplayName(), AppConfig.getPreConfigAddressInfo().getDisplayAddressDetail()/*, R.drawable.ar_icon*/);
        }
    }

    /**
     * 刷新数据
     */
    private void refreshData() {
        ApiUser.getMeInfo(new Callback<MeInfo>() {
            @Override
            public void onResponse(Call<MeInfo> call, Response<MeInfo> res) {
                if (res != null && res.body() != null) {
                    setMeInfo(res.body());
                    if (BuildConfig.DEBUG && TextUtils.isEmpty(res.body().getAvatar()))
                        ToastHelper.show("没有头像");
                } else if (BuildConfig.DEBUG) {
                    ToastHelper.show("获取个人信息错误");
                }
            }

            @Override
            public void onFailure(Call<MeInfo> call, Throwable t) {
            }
        });

        // 获取地址
        refreshAddress();

        // 收货时间
        refreshRecvTime();

        // 发票
        refreshBill();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (R.id.iv_header == id || R.id.tv_name == id) {
            //gotoEditUserInfo();
            if (!LoginCommon.isLogin()) {
                LoginCommon.gotoLogin(getActivity());
            }
        } else if (R.id.tv_register == id) {
            gotoRegister();
        } else if (R.id.ll_coupon == id) {
            gotoCoupon();
        } else if (R.id.ll_favorite == id) {
            gotoFavorite();
        } else if (R.id.it_order == id) {
            gotoOrder();
        } else if (R.id.ll_address == id) {
            gotoAddress();
        } else if (R.id.tv_account_man == id) {
            new AlertDialog.Builder(getContext())
                    .setTitle("退出")
                    .setMessage("确定退出登录？")
                    .setPositiveButton("确定", (dialogInterface, i) -> LoginCommon.logout())
                    .setNegativeButton("取消", null)
                    .show();
        }
    }

    /**
     * 编辑个人信息
     */
    private void gotoEditUserInfo() {
        //UserInfoActivity.gotoActivityWithLogin(getActivity(), UserInfoActivity.class, true);
    }

    /**
     * 跳转到登录
     */
    private void gotoLogin() {
        LoginActivity.gotoActivity(getActivity(), LoginActivity.class, true);
    }

    /**
     * 跳转到注册
     */
    private void gotoRegister() {
        RegisterActivity.gotoActivity(getActivity(), RegisterActivity.class, true);
    }

    /**
     * 跳转到优惠券
     */
    private void gotoCoupon() {
        CouponActivity.gotoActivityWithLogin(getActivity(), CouponActivity.class, true);
    }

    /**
     * 跳转到收藏
     */
    private void gotoFavorite() {
        FavoriteActivity.gotoActivityWithLogin(getActivity(), FavoriteActivity.class, true);
    }

    /**
     * 跳转到订单
     */
    private void gotoOrder() {
        OrderActivity.gotoOrder(getActivity(), 0);
    }

    /**
     * 跳转到收货地址列表
     */
    private void gotoAddress() {
        AddressActivity.gotoActivity(getActivity(), AddressActivity.class);
    }

    /**
     * 设置数据
     */
    public void setMeInfo(MeInfo info) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        if (info == null || TextUtils.isEmpty(info.getAvatar())) {
            mHeadPic.setImageDrawable(null);
            RoundingParams roundingParams = new RoundingParams();
            roundingParams.setRoundAsCircle(true);
            GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
            GenericDraweeHierarchy hierarchy = builder
                    .setFadeDuration(300)
                    .setPlaceholderImage(R.drawable.me_avatar_default)
                    .setRoundingParams(roundingParams)
                    .build();
            mHeadPic.setHierarchy(hierarchy);
        } else {
            mHeadPic.setImageURI(info.getAvatar());
        }

        if (info == null) {
            mTvName.setText("登录");
        } else {
            setNickName(info.getNickname());
        }

        if (info != null)
            AppConfig.saveMeInfo(info);

        mTvCouponCnt.setText("" + (info == null ? 0 : info.getCouponCount()));
        mTvFavCnt.setText("" + (info == null ? 0 : info.getFavoriteCount()));
    }

    /**
     * 设置昵称
     * @param nick
     */
    private void setNickName(String nick) {
        if (TextUtils.isEmpty(nick))
            nick = LoginCommon.getUserAccount();
        // 没有昵称用账号名
        mTvName.setText(nick);
    }

    /**
     * 选择收货时间
     */
    private void showRecvTimeDialog() {
        if (!LoginCommon.isLogin()) {
            LoginCommon.gotoLogin(getActivity());
            return;
        }
        new AlertDialog.Builder(getContext())
                .setTitle("收货时间")
                //.setView(new RecvDateView(getContext()))
                .setSingleChoiceItems(RECV_TIME, AppConfig.getPreConfigRecvTime(), (dialog, which) -> {
                    dialog.dismiss();
                    AppConfig.savePreConfigRecvTime(which);
                    refreshRecvTime();
                })
                .show();
    }

    /**
     * 刷新收货时间
     */
    private void refreshRecvTime() {
        int recvTime = AppConfig.getPreConfigRecvTime();
        if (recvTime < 0 || recvTime >= RECV_TIME.length)
            recvTime = 2;
        mItReceiveTime.updateDesc(RECV_TIME[recvTime]);
    }

    /**
     * 刷新发票
     */
    private void refreshBill() {
        String billInfo = AppConfig.getPreConfigBillInfo();
        if (TextUtils.isEmpty(billInfo)) {
            mItBillInfo.updateDesc("普通个人电子发票");
        } else {
            mItBillInfo.updateDesc(billInfo);
        }
    }
}
